package com.qinhao.loveCrowdFunding.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qinhao.loveCrowdFunding.bean.AliReturnPayBean;
import com.qinhao.loveCrowdFunding.config.AliPayConfig;
import com.qinhao.loveCrowdFunding.handler.MyMessageHandler;
import com.qinhao.loveCrowdFunding.req.PayRequest;
import com.qinhao.loveCrowdFunding.req.UpdateNameByIdRequest;
import com.qinhao.loveCrowdFunding.resp.UpdateNameByIdResponse;
import com.qinhao.loveCrowdFunding.service.IntegralService;
import com.qinhao.loveCrowdFunding.service.PayService;
import com.qinhao.loveCrowdFunding.utils.AlipayMapUtil;
import com.qinhao.loveCrowdFunding.utils.RandomOrderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@PropertySource("classpath:alipayRequestConfig.properties")
@CrossOrigin
@RequestMapping("/ali")
public class PayConfigController {
    @Autowired
    private AlipayClient alipayClient;
    //异步通知接口
    @Value("${alipayRequest.notifyUrl}")
    private String notifyUrl;
    @Autowired
    PayService payService;
    @Autowired
    MyMessageHandler myMessageHandler;
    @Autowired
    private AdminController adminController;
    @Autowired
    private IntegralService integralService;

    /**
     * 支付接口
     * @param response
     * @throws IOException
     */
    @RequestMapping("/pay")
    public void send(HttpServletResponse response, PayRequest payRequest) throws IOException {
        payRequest.setTitle(new String(payRequest.getTitle().getBytes("iso-8859-1"),"utf-8"));
        System.out.println(payRequest.getTitle());
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
        //设置异步通知接口
        alipayTradePagePayRequest.setNotifyUrl("http://www.fangaoxs.top:8080/ali/call");
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new RandomOrderUtil().generateOid();
        //付款金额，必填
        String total_amount = payRequest.getDonateCount().toString();
        //订单名称，必填
        String subject = "捐赠项目";
        //商品描述，可空
        String body = "众筹项目捐赠";
        alipayTradePagePayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayTradePagePayRequest).getBody();
            AlipayMapUtil.hashMap.put(out_trade_no, payRequest);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    @RequestMapping("/call")
    public void call(HttpServletRequest request, HttpServletResponse response, AliReturnPayBean returnPay) throws IOException {
        response.setContentType("type=text/html;charset=UTF-8");
        if (!AliPayConfig.checkSign(request)) {
            response.getWriter().write("failure");
            return;
        }
        if (returnPay == null) {
            response.getWriter().write("success");
            return;
        }
        //表示支付成功状态下的操作
        if (returnPay.getTrade_status().equals("TRADE_SUCCESS")) {
            String out_trade_no = returnPay.getOut_trade_no();
            PayRequest payRequest = AlipayMapUtil.hashMap.get(out_trade_no);
            try {
                payService.addPay(payRequest);
                String message = "你的捐赠款" + payRequest.getDonateCount() + "已经到达标题为" + payRequest.getTitle() + "的用户账户，感谢你的捐赠";
                String messageTmp = "你的标题为" + payRequest.getTitle() + "的众筹项目收到一笔" + payRequest.getDonateCount() + "的捐赠款项，恭喜";
                adminController.sendMessage(message, payRequest.getUserId());
                adminController.sendMessage(messageTmp, payRequest.getSimpleUserId());
                integralService.addIntegralChange(10, payRequest.getUserId(), "捐赠项目 " + payRequest.getTitle() + " 成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
